package cn.edu.neusoft.demo.hospital2.Controller;

import cn.edu.neusoft.demo.hospital2.Service.impl.AppointmentServiceImpl;
import cn.edu.neusoft.demo.hospital2.common.BusinessException;
import cn.edu.neusoft.demo.hospital2.common.ResourceNotFoundException;
import cn.edu.neusoft.demo.hospital2.pojo.Department;
import cn.edu.neusoft.demo.hospital2.pojo.DoctorWork;
import cn.edu.neusoft.demo.hospital2.pojo.PatientDoctor;
import cn.edu.neusoft.demo.hospital2.Service.AppointmentService;
import cn.edu.neusoft.demo.hospital2.pojo.dto.DepartmentStatsDTO;
import cn.edu.neusoft.demo.hospital2.pojo.dto.RegistrationDTO;
import cn.edu.neusoft.demo.hospital2.pojo.dto.RegistrationDetailDTO;
import cn.edu.neusoft.demo.hospital2.pojo.dto.RegistrationQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@Tag(name = "挂号预约相关的api")
@RequestMapping("/api/appointment")
public class AppointmentController {

    @Autowired
    private AppointmentService appointmentService;

    @Autowired
    private AppointmentServiceImpl registrationService;

    // 查询医生出诊信息
    @GetMapping("/list")
    public Map<String, Object> getDoctorWorkList(DoctorWork doctorWork) {
        Map<String, Object> result = new HashMap<>();
        List<DoctorWork> list = appointmentService.getDoctorWorkList(doctorWork);
        result.put("code", 200);
        result.put("data", list);
        result.put("message", "查询成功");
        return result;
    }

    // 预约挂号
    @PostMapping("/make")
    public Map<String, Object> makeAppointment(@RequestBody PatientDoctor patientDoctor) {
        Map<String, Object> result = new HashMap<>();
        boolean success = appointmentService.makeAppointment(patientDoctor);
        if (success) {
            result.put("code", 200);
            result.put("message", "预约成功");
        } else {
            result.put("code", 500);
            result.put("message", "预约失败");
        }
        return result;
    }

    // 取消预约
    @PostMapping("/cancel")
    public Map<String, Object> cancelAppointment(@RequestParam("id") Integer id) {
        Map<String, Object> result = new HashMap<>();
        boolean success = appointmentService.cancelAppointment(id);
        if (success) {
            result.put("code", 200);
            result.put("message", "取消预约成功");
        } else {
            result.put("code", 500);
            result.put("message", "取消预约失败");
        }
        return result;
    }

    // 根据患者ID查询预约记录
    @GetMapping("/listByPatientId")
    public Map<String, Object> getAppointmentsByPatientId(@RequestParam("patientId") String patientId) {
        Map<String, Object> result = new HashMap<>();
        List<PatientDoctor> list = appointmentService.getAppointmentsByPatientId(patientId);
        result.put("code", 200);
        result.put("data", list);
        result.put("message", "查询成功");
        return result;
    }

    // 根据ID查询预约记录
    @GetMapping("/{id}")
    public Map<String, Object> getAppointmentById(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        PatientDoctor appointment = appointmentService.getAppointmentById(id);
        if (appointment != null) {
            result.put("code", 200);
            result.put("data", appointment);
            result.put("message", "查询成功");
        } else {
            result.put("code", 404);
            result.put("message", "未找到该预约记录");
        }
        return result;
    }

    // 更新预约记录
    @PutMapping("/update")
    public Map<String, Object> updateAppointment(@RequestBody PatientDoctor patientDoctor) {
        Map<String, Object> result = new HashMap<>();
        boolean success = appointmentService.updateAppointment(patientDoctor);
        if (success) {
            result.put("code", 200);
            result.put("message", "更新预约成功");
        } else {
            result.put("code", 500);
            result.put("message", "更新预约失败");
        }
        return result;
    }

    // 查询所有预约记录
    @GetMapping("/all")
    public Map<String, Object> getAllAppointments() {
        Map<String, Object> result = new HashMap<>();
        List<PatientDoctor> list = appointmentService.getAllAppointments();
        result.put("code", 200);
        result.put("data", list);
        result.put("message", "查询成功");
        return result;
    }

    @Operation(summary = "分页查询挂号记录")
    @GetMapping
    public ResponseEntity<Page<RegistrationDTO>> getRegistrations(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String patientName,
            @RequestParam(required = false) String doctorName,
            @RequestParam(required = false) String departmentId,
            @RequestParam(required = false) String status,
            @PageableDefault(page = 0, size = 10, sort = "day", direction = Sort.Direction.DESC) Pageable pageable) {

        RegistrationQuery query = new RegistrationQuery();
        query.setStartDate(startDate);
        query.setEndDate(endDate);
        query.setPatientName(patientName);
        query.setDoctorName(doctorName);
        query.setDepartmentId(departmentId);
        query.setStatus(status);

        Page<RegistrationDTO> result = registrationService.getRegistrations(query, pageable);
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "获取科室树形结构",description = "获取科室树形结构只包括一级和二级科室的树结构")
    @GetMapping("/departments/tree")
    public ResponseEntity<List<Department>> getDepartmentTree() {
        List<Department> tree = registrationService.getDepartmentTree();
        return ResponseEntity.ok(tree);
    }

    @Operation(summary = "获取挂号详情")
    @GetMapping("/registration/{id}")
    public ResponseEntity<RegistrationDetailDTO> getRegistrationDetail(@PathVariable Integer id) {
        RegistrationDetailDTO detail = registrationService.getRegistrationDetail(id);
        return ResponseEntity.ok(detail);
    }

    @Operation(summary = "取消挂号")
    @PostMapping("/{id}/cancel")
    public ResponseEntity<Void> cancelRegistration(@PathVariable Integer id) {
        registrationService.cancelRegistration(id);
        return ResponseEntity.ok().build();
    }

    @Operation(summary = "科室挂号量统计")
    @GetMapping("/stats/department")
    public ResponseEntity<List<DepartmentStatsDTO>> getDepartmentStats() {
        List<DepartmentStatsDTO> stats = registrationService.getDepartmentStats();
        return ResponseEntity.ok(stats);
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<String> handleBusinessError(BusinessException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }
}